package com.java.socket.udp.mulitclient.whileloop.receiver;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.nio.charset.Charset;

/**
 * 多客户端udp socket通信服务端程序
 * <p>使用while死循环的方式</p>
 *
 * @author xzmeasy
 * @version 1.0
 * @since 星期一 十二月,2018
 */
@SuppressWarnings("Duplicates")
public class DatagramReceiver {

    public static void main(String[] args) {
        try {
            // 创建DatagramSocket，监听指定的端口号
            DatagramSocket receiveSocket = new DatagramSocket(8888);
            DatagramSocket sendSocket = new DatagramSocket();
            while (true) {
                // 创建保存从发送方接收到的数据的数据包
                byte[] receiveData = new byte[1024];
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                // 接收数据
                receiveSocket.receive(receivePacket);
                System.out.println("从发送方接收到的数据: " + new String(receivePacket.getData(), Charset.forName("utf-8")) + ", 数据来自" + receivePacket.getSocketAddress().toString());
                // 此处不能关闭资源
//                receiveSocket.close();


                // 向发送方反馈数据
                // 创建要反馈到发送方的数据包
                byte[] sendData = "接收方反馈的数据".getBytes();
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length);
                sendPacket.setAddress(InetAddress.getByName("localhost"));
                sendPacket.setPort(8889);
                // 发送数据
                sendSocket.send(sendPacket);
                // 关闭资源
//                sendSocket.close();
            }
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
